//
//  ViewController.m
//  验证码Demo
//
//  Created by 王治亮 on 16/6/23.
//  Copyright © 2016年 王治亮. All rights reserved.
//

#import "ViewController.h"
#import "AFNetworking/AFNetworking.h"
#import "GDataXMLNode.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;

@end

@implementation ViewController{
    NSString *code;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //
}
- (IBAction)code:(id)sender {
    [self getCode];//调用之前做号码的判断

}
- (IBAction)reg:(id)sender {
    
    if ([_codeTextField.text isEqualToString:code]) {
        //验证通过
        //这里你再写提交注册的代码
        //...........
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)getCode{
    NSString *soapStr = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                         "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                         "<soap:Body>"
                         "<ChuangLan xmlns=\"http://liulongzhu.com/\">"
                         "<strCellNumber>%@</strCellNumber>"
                         "<strType>%@</strType>"
                         "</ChuangLan>"
                         "</soap:Body>"
                         "</soap:Envelope>",_phoneTextField.text,@"0"];
    
    //    NSLog(@"%@",soapStr);
    
    NSURL *url = [NSURL URLWithString:@"http://we.liulongzhu.com/Service/WebServiceForApp.asmx"];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    NSString *soapLength = [NSString stringWithFormat:@"%d", [soapStr length]];
    [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    [theRequest addValue: @"http://liulongzhu.com/ChuangLan" forHTTPHeaderField:@"SOAPAction"];
    [theRequest addValue: soapLength forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPMethod:@"POST"];
    
    [theRequest setHTTPBody: [soapStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/xml"];
    
    NSURLSessionDataTask *task = [manager dataTaskWithRequest:theRequest completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        NSString *xml = [[NSString alloc] initWithData:(NSData *)responseObject encoding:NSUTF8StringEncoding];
        
        NSDictionary *ss = [self getWebServiceXMLResult:xml xpath:@"ChuangLanResult"];
        
        
        code = [ss[@"text"] substringWithRange:NSMakeRange(2, 6)];
        NSLog(@"验证码是%@",code);
    }];
    [task resume];

}

- (NSDictionary *)getWebServiceXMLResult:(NSString *) content xpath:(NSString *)path
{
    content = [content stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
    content = [content stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    content = [content stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    if (![content hasPrefix:@"<?xml version"]) {
        return [NSJSONSerialization JSONObjectWithData:[content dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
    }else{
        NSMutableDictionary *resultDict = [[NSMutableDictionary alloc] init];
        content = [content stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
        content = [content stringByReplacingOccurrencesOfString:@">" withString:@">"];
        content = [content stringByReplacingOccurrencesOfString:@"xmlns" withString:@"noNSxml"];
        NSError *docError = nil;
        GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithXMLString:content options:0 error:&docError];
        if(!docError)
        {
            NSArray *children = nil;
            children = [document nodesForXPath:[NSString stringWithFormat:@"//%@",path] error:&docError];
            if(!docError)
            {
                if(children && [children count]>0)
                {
                    GDataXMLElement *rootElement = (GDataXMLElement *)[children objectAtIndex:0];
                    NSArray *nodearr = [rootElement children];
                    for (int i = 0; i<[nodearr count]; i++) {
                        GDataXMLElement *element = (GDataXMLElement *)[nodearr objectAtIndex:i];
                        [resultDict setObject:[element stringValue] forKey:[element name]];
                    }
                }
            }
        }
        return resultDict;
//        if ([resultDict allKeys].count > 0) {
//            NSData *data =[resultDict[@"text"] dataUsingEncoding:NSUTF8StringEncoding];
//            NSError *error;
//            resultDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
//            if (error !=nil ) {
//                NSLog(@"%@",error);
//            }
//            // NSLog(@"connectionDidFinishLoading %@",jsons);
//            return resultDict;
//        }else{
//            return resultDict;
//        }
    }
    
    /*
     1、获取GDataXMLNode.h/m文件，将GDataXMLNode.h/m文件添加到工程中
     2、向工程中增加“libxml2.dylib”库
     3、在工程的“Build Settings”页中找到“Header Search Path”项，添加/usr/include/libxml2"到路径中
     4、添加“GDataXMLNode.h”文件到头文件中，如工程能编译通过，则说明GDataXMLNode添加成功
     */
    
}
@end
